package com.macro.mall.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.constant.RedisConstant;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.mapper.OmsCartItemMapper;
import com.macro.mall.model.OmsCartItem;
import com.macro.mall.model.OmsCartItemExample;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.dao.PortalProductDao;
import com.macro.mall.portal.domain.CartProduct;
import com.macro.mall.portal.domain.CartPromotionItem;
import com.macro.mall.portal.service.OmsCartItemService;
import com.macro.mall.portal.service.OmsPromotionService;
import com.macro.mall.portal.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车管理Service实现类
 * Created by macro on 2018/8/2.
 */
@Service
public class OmsCartItemServiceImpl implements OmsCartItemService {
    @Autowired
    private OmsCartItemMapper cartItemMapper;
    @Autowired
    private PortalProductDao productDao;
    @Autowired
    private OmsPromotionService promotionService;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private RedisService redisService;

    @Override
    public int add(OmsCartItem cartItem) {
        int count = 0;
        UmsMember currentMember =memberService.getCurrentMember();
        cartItem.setMemberId(currentMember.getId());
        cartItem.setMemberNickname(currentMember.getNickname());
        cartItem.setDeleteStatus(0);
        //三级缓存
        OmsCartItem existCartItemRedisCache = (OmsCartItem)redisService.hGet(RedisConstant.REDIS_CART_ITEM_CACHE+currentMember.getId(), cartItem.getProductId().toString());
        if(existCartItemRedisCache==null){
            //查询数据库
            OmsCartItem existCartItem = getCartItem(cartItem);
            if(existCartItem==null){
                cartItem.setCreateDate(new Date());
                count = cartItemMapper.insert(cartItem);
                //存储数量
                redisService.hSet(RedisConstant.REDIS_CART_ITEM_CACHE+currentMember.getId(),cartItem.getProductId()+RedisConstant.REDIS_CART_ITEM_CACHE_FIELD1,cartItem.getQuantity(),30*24*60*60);
            }else{
                cartItem.setModifyDate(new Date());
                existCartItem.setQuantity(existCartItem.getQuantity() + cartItem.getQuantity());
                count = cartItemMapper.updateByPrimaryKey(existCartItem);
                redisService.hSet(RedisConstant.REDIS_CART_ITEM_CACHE+currentMember.getId(),cartItem.getProductId()+RedisConstant.REDIS_CART_ITEM_CACHE_FIELD1,existCartItem.getQuantity() + cartItem.getQuantity(),30*24*60*60);
            }
            //存储信息
            redisService.hSet(RedisConstant.REDIS_CART_ITEM_CACHE+currentMember.getId(), cartItem.getProductId()+RedisConstant.REDIS_CART_ITEM_CACHE_FIELD2,JSONObject.toJSON(cartItem),30*24*60*60);

        }else{
            redisService.hIncr(RedisConstant.REDIS_CART_ITEM_CACHE+currentMember.getId(),cartItem.getProductId()+RedisConstant.REDIS_CART_ITEM_CACHE_FIELD1,1L);
        }
        return count;
    }

    /**
     * 根据会员id,商品id和规格获取购物车中商品
     */
    private OmsCartItem getCartItem(OmsCartItem cartItem) {
        OmsCartItemExample example = new OmsCartItemExample();
        OmsCartItemExample.Criteria criteria = example.createCriteria().andMemberIdEqualTo(cartItem.getMemberId())
                .andProductIdEqualTo(cartItem.getProductId()).andDeleteStatusEqualTo(0);
        if (cartItem.getProductSkuId()!=null) {
            criteria.andProductSkuIdEqualTo(cartItem.getProductSkuId());
        }
        List<OmsCartItem> cartItemList = cartItemMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(cartItemList)) {
            return cartItemList.get(0);
        }
        return null;
    }

    @Override
    public List<OmsCartItem> list(Long memberId) {
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andMemberIdEqualTo(memberId);
        return cartItemMapper.selectByExample(example);
    }

    @Override
    public List<CartPromotionItem> listPromotion(Long memberId, List<Long> cartIds) {
        List<OmsCartItem> cartItemList = list(memberId);
        if(CollUtil.isNotEmpty(cartIds)){
            cartItemList = cartItemList.stream().filter(item->cartIds.contains(item.getId())).collect(Collectors.toList());
        }
        List<CartPromotionItem> cartPromotionItemList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(cartItemList)){
            cartPromotionItemList = promotionService.calcCartPromotion(cartItemList);
        }
        return cartPromotionItemList;
    }

    @Override
    public int updateQuantity(Long id, Long memberId, Integer quantity,Long productId,Long productSkuId) {
        int count = 0;
        OmsCartItem cartItem = new OmsCartItem();
        cartItem.setQuantity(quantity);
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andDeleteStatusEqualTo(0)
                .andIdEqualTo(id).andMemberIdEqualTo(memberId);
        count = cartItemMapper.updateByExampleSelective(cartItem, example);
        if(redisService.hHasKey(RedisConstant.REDIS_CART_ITEM_CACHE+memberId,productId+RedisConstant.REDIS_CART_ITEM_CACHE_FIELD1)){
            redisService.hIncr(RedisConstant.REDIS_CART_ITEM_CACHE+memberId,productId+RedisConstant.REDIS_CART_ITEM_CACHE_FIELD1,1L);
        }else{
            cartItem = new OmsCartItem();
            cartItem.setMemberId(memberId);
            cartItem.setProductId(productId);
            cartItem.setProductSkuId(productSkuId);
            OmsCartItem existcartItem = getCartItem(cartItem);
            //购物车商品数量信息
            redisService.hSet(RedisConstant.REDIS_CART_ITEM_CACHE+memberId,productId+RedisConstant.REDIS_CART_ITEM_CACHE_FIELD1,quantity,30*24*60*60);
            //购物车商品信息
            redisService.hSet(RedisConstant.REDIS_CART_ITEM_CACHE+memberId,productId+RedisConstant.REDIS_CART_ITEM_CACHE_FIELD2,JSONObject.toJSON(existcartItem),30*24*60*60);
        }
        return count;
    }

    @Override
    public int delete(Long memberId, List<Long> ids) {
        OmsCartItem record = new OmsCartItem();
        record.setDeleteStatus(1);
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andIdIn(ids).andMemberIdEqualTo(memberId);
        return cartItemMapper.updateByExampleSelective(record, example);
    }

    @Override
    public CartProduct getCartProduct(Long productId) {
        return productDao.getCartProduct(productId);
    }

    @Override
    public int updateAttr(OmsCartItem cartItem) {
        //删除原购物车信息
        OmsCartItem updateCart = new OmsCartItem();
        updateCart.setId(cartItem.getId());
        updateCart.setModifyDate(new Date());
        updateCart.setDeleteStatus(1);
        cartItemMapper.updateByPrimaryKeySelective(updateCart);
        cartItem.setId(null);
        add(cartItem);
        return 1;
    }

    @Override
    public int clear(Long memberId) {
        OmsCartItem record = new OmsCartItem();
        record.setDeleteStatus(1);
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        return cartItemMapper.updateByExampleSelective(record,example);
    }
}
